<template>
  <div class="materialEditOrAdd" style="height： 100vh;">
    <div class="crumbs-box">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/content/list?tabsName=Material' }">内容管理</el-breadcrumb-item>
        <el-breadcrumb-item v-if="$route.query && $route.query.param">编辑平台资源</el-breadcrumb-item>
        <el-breadcrumb-item v-else>添加平台资源</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="content-box">
      <div class="material-title">上传平台资源</div>

      <div class="teaching-box">
        <div class="title">基本信息</div>
        <el-form
          ref="ruleForm"
          :rules="rules"
          class="teaching-form"
          label-width="140px"
          :model="ruleForm"
        >
          <el-form-item label="名称：" prop="name">
            <el-col :span="12">
              <el-input v-model="ruleForm.name" placeholder="请输入名称" />
            </el-col>
          </el-form-item>
          <el-form-item label="类型：" prop="type">
            <el-col :span="12">
              <el-select v-model="ruleForm.type" style="width: 100%;" placeholder="请选择类型">
                <el-option
                  v-for="item in filesTpye"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="分类：" prop="categoryList">
            <el-col :span="16">
              <category
                v-if="ruleForm && ruleForm.GROWTH_CLASSIFY"
                :list="ruleForm"
                biz-type-enum="RES_PLATFORM"
                @Callback="categoryCallback"
              />
            </el-col>
          </el-form-item>
          <el-form-item label="栏目：" prop="region">
            <el-col :span="12">
              <el-cascader
                v-model="ruleForm.categorySelect"
                :options="options.category"
                style="width: 100%;"
                :disabled="options.category && options.category.length > 0 ? false : true"
                :props="{
                  multiple: true,
                  value: 'tagsId',
                  label: 'tagsName',
                  children: 'sub',
                  checkStrictly: true
                }"
                clearable
              />
            </el-col>
          </el-form-item>
          <el-form-item label="标签：" prop="region">
            <el-col :span="12">
              <el-cascader
                v-model="ruleForm.contentSelect"
                :options="options.content"
                :disabled="options.content && options.content.length > 0 ? false : true"
                style="width: 100%;"
                :props="{
                  multiple: true,
                  value: 'tagsId',
                  label: 'tagsName',
                  children: 'sub',
                  checkStrictly: true
                }"
                clearable
              />
            </el-col>
          </el-form-item>

          <el-form-item label="文件">
            <el-col :span="12">
              <el-upload
                class="upload-demo"
                :action="action"
                :header="uploadHeader"
                :data="uploadForm"
                :show-file-list="true"
                :on-success="uploadSuccess"
                :before-upload="beforeUpload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :file-list="ruleForm.files"
                :limit="1"
                :on-exceed="handleExceed"
              >
                <el-button size="small" icon="el-icon-upload2">上传文件</el-button>
                <div slot="tip" class="el-upload__tip">支持扩展名：.txt .ppt .xls .doc .docx .pdf .mp4 ...</div>
              </el-upload>
            </el-col>
          </el-form-item>
        </el-form>
      </div>

      <div class="button-box">
        <button class="default" @click="cancel">取消</button>
        <button class="submit" @click="onSubmit('ruleForm')">发布</button>
      </div>
    </div>
  </div>
</template>

<script>
import { preUpload } from '@/api/uploads';
import { resPlatform, resPlatformDel, resPlatformDetail, findColumnTags, findTagsList, resPlatformSave, resPlatformUpdate } from '@/api/content';
import category from '@/components/Category';
import { filesType } from './data';
import { reduceArr, assignment, compose, tagsObjSwitch } from '@/utils/categoryOrTags';

export default {
  name: 'MaterialEditOrAdd',
  components: { category },
  data() {
    return {
      action: 'https://yes910-pub.obs.cn-south-1.myhuaweicloud.com',
      uploadHeader: {
        'Content-Type': 'multipart/form-data'
      },
      msg: 'msg父级',
      filesTpye: filesType,
      uploadForm: {},
      options: {
        category: null, // 分类标签
        content: null // 内容标签
      },
      ruleForm: {

      },
      rules: {
        name: [
          { required: true, message: '请输入标题!', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择教研活动!', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    if (this.$route.query.param) {
      this.init();
    } else {
      var arr = ['GROWTH_CLASSIFY', 'STAGE', 'SUBJECT'];
      arr.map(item => {
        this.ruleForm[item] = {
          itemCode: '',
          cateId: ''
        };
      });
      console.log('this.ruleForm:', this.ruleForm);
    }
  },
  methods: {
    // 获取选项
    async getSelection() {
      if (this.ruleForm.GROWTH_CLASSIFY.itemCode && this.ruleForm.STAGE.itemCode && this.ruleForm.SUBJECT.itemCode) {
        await this.getFindColumnTags();
        await this.getFindTagsList();
      }
    },
    // 获取分类标签
    getFindColumnTags() {
      findColumnTags({
        growthClassify: this.ruleForm.GROWTH_CLASSIFY.itemCode || '',
        stageId: this.ruleForm.STAGE.itemCode || '',
        subjectId: this.ruleForm.SUBJECT.itemCode || ''
      }).then(res => {
        this.options.category = assignment(res.data);

        var categorySelect = [];
        if (this.ruleForm.newCategoryTag && this.ruleForm.newCategoryTag.length > 0) {
          this.ruleForm.newCategoryTag.map(item => {
            var items = this.options.category.filter(items => items.tagsId === item.tagsId);
            if (this.checkArr(items)) {
              categorySelect.push([items[0].tagsId]);
            }
          });
        }
        this.ruleForm.categorySelect = categorySelect;
      });
    },

    // 获取标签
    getFindTagsList() {
      findTagsList({
        growthClassify: this.ruleForm.GROWTH_CLASSIFY.itemCode || '',
        stageId: this.ruleForm.STAGE.itemCode || '',
        subjectId: this.ruleForm.SUBJECT.itemCode || '',
        tagsKindEnum: 'TEACHING_DESIGN',
        tagsTypeEnum: 'CATEGORY_TAGS'
      }).then(res => {
        this.options.content = assignment(res.data);

        var contentSelect = [];
        if (this.ruleForm.newColumnTag && this.ruleForm.newColumnTag.length > 0) {
          this.ruleForm.newColumnTag.map(item => {
            var items = this.options.content.filter(items => items.tagsId === item.tagsId);
            contentSelect.push([items[0].tagsId]);
          });
        }
        this.ruleForm.contentSelect = contentSelect;
      });
    },
    init() {
      resPlatformDetail({ id: this.$route.query.param }).then(res => {
        var arr = ['GROWTH_CLASSIFY', 'STAGE', 'SUBJECT'];
        arr.map(item => {
          var items = res.data.categoryList.filter(items => items.groupEnum === item);
          res.data[item] = items[0] ? items[0] : { itemCode: '', cateId: '' };
        });
        this.ruleForm = res.data;

        var cateObj = {};
        for (var i in this.ruleForm.categoryTag) {
          Object.assign(cateObj, this.ruleForm.categoryTag[i].tags);
          // cateArr = cateArr.concat(this.ruleForm.categoryTag[i].tags);
        }
        this.ruleForm.newCategoryTag = tagsObjSwitch(cateObj);
        // console.log('newCategoryTag:', this.ruleForm.newCategoryTag);
        this.ruleForm.newColumnTag = tagsObjSwitch(this.ruleForm.columnTag.tags);

        this.ruleForm.files = [];
        this.ruleForm.files.push({
          name: this.ruleForm.fileUrl,
          url: this.ruleForm.fileUrl
        });
        this.getSelection();
      });
    },

    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleRemove(file, fileList) {
      this.ruleForm.files = fileList;
    },
    handlePreview(file) {
      console.log(file);
    },
    beforeRemove(file, fileList) {
      console.log('素材:', file, fileList);
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    uploadSuccess(res, file) {
      this.ruleForm.files = [];
      this.ruleForm.files.push({
        name: file.name,
        url: this.ruleForm.fileUrl
      });
      console.log(this.ruleForm.files);
      // this.form.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeUpload(file) {
      // const imgStr = /\.(jpg|jpeg|png|JPG|PNG|JPEG)$/;
      // if (!imgStr.test(file.name)) {
      //   this.$message.error('上传格式不对，请重新上传!');
      //   return false;
      // }
      let continueUpload = false;
      return new Promise((resolve, reject) => {
        preUpload({
          biz: 'OPEN',
          name: file.name,
          size: file.size
        }).then(res => {
          // console.log('文件上传：', res.data);
          this.action = res.data.action;
          this.uploadForm = res.data.parameters;
          this.ruleForm.fileUrl = res.data.uri;
          continueUpload = true;
          resolve(continueUpload);
        }).catch(err => {
          reject(continueUpload);
        });
      });
    },

    categoryCallback(obj) {
      this.ruleForm = obj;
      this.getSelection();
    },
    cancel() {
      this.$router.push({
        path: '/content/list',
        query: { tabsName: 'Material' }
      });
    },
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // console.log('submit!!');
          // 分类
          if (this.checkArr(this.ruleForm.categorySelect)) {
            this.ruleForm.categoryTag = [];
            this.options.category = reduceArr(this.options.category);
            this.ruleForm.categorySelect.map(item => {
              var items = this.options.category.filter(
                data => item[0] === data.tagsId
              );

              if (items[0]) {
                this.ruleForm.categoryTag.push({
                  id: items[0].tagsId,
                  name: items[0].tagsName
                });
              }
            });
          } else {
            this.ruleForm.categoryTag = [];
          }

          // 标签
          if (this.checkArr(this.ruleForm.contentSelect)) {
            this.ruleForm.columnTag = [];
            this.options.content = reduceArr(this.options.content);
            this.ruleForm.contentSelect.map(item => {
              var items = this.options.content.filter(
                data => item[0] === data.tagsId
              );

              if (items[0]) {
                this.ruleForm.columnTag.push({
                  id: items[0].tagsId,
                  name: items[0].tagsName
                });
              }
            });
          } else {
            this.ruleForm.columnTag = [];
          }
          this.ruleForm.categoryTypeList = [];
          this.ruleForm.categoryTypeList.push(this.ruleForm.GROWTH_CLASSIFY);
          this.ruleForm.categoryTypeList.push(this.ruleForm.STAGE);
          this.ruleForm.categoryTypeList.push(this.ruleForm.SUBJECT);
          if (this.$route.query.param) {
            resPlatformUpdate(this.ruleForm).then(res => {
              this.$message({
                message: '修改成功',
                type: 'success'
              });
              this.$router.push({
                path: '/content/list',
                query: { tabsName: 'Material' }
              });
            });
          } else {
            resPlatformSave(this.ruleForm).then(res => {
              this.$message({
                message: '添加成功',
                type: 'success'
              });
              this.$router.push({
                path: '/content/list',
                query: { tabsName: 'Material' }
              });
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.avatar-uploader {
  width: 480px;
  height: 270px;
  background: rgba(0, 0, 0, 0.02) !important;
  border-radius: 16px;
  border: 1px dashed rgba(0, 0, 0, 0.15);
  border-radius: 8px;
  cursor: pointer;
  .icon-text {
    width: 200px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.step {
  span {
    margin: 0 8px;
  }
  .el-input {
    width: 90% !important;
  }
  .step-btn {
    margin-left: 20px;
    margin-top: 10px;
  }
}

.materialEditOrAdd {
  .content-box {
    padding: 40px;
    background: rgba(245, 246, 250, 1);
    .material-title {
      font-size: 20px;
      font-family: MicrosoftYaHei;
      color: rgba(0, 0, 0, 0.85);
      line-height: 28px;
    }

    .teaching-box {
      background-color: white;
      margin-top: 24px;
      padding-bottom: 16px;
      border-radius: 16px;
      .title {
        border-bottom: 1px solid #d9d9d9;
        line-height: 46px;
        padding: 0 40px;
        font-size: 16px;
        font-family: MicrosoftYaHei;
        color: rgba(0, 0, 0, 0.85);
      }

      .teaching-form {
        margin-top: 40px;
        padding: 0 40px;
      }
      .textarea {
        height: 300px;
        padding: 20px;
        background: rgba(0, 0, 0, 0.02);
        border-radius: 4px;
        border: 1px solid rgba(0, 0, 0, 0.15);
      }
    }

    .uploader-text-box {
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .button-box {
      margin-top: 24px;
      .default {
        width: 94px;
        height: 40px;
        background: rgba(255, 255, 255, 1);
        border-radius: 4px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        margin-right: 30px;
        cursor: pointer;
      }
      .submit {
        width: 128px;
        height: 40px;
        border: none;
        background: rgba(84, 184, 123, 1);
        border-radius: 4px;

        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(255, 255, 255, 1);
        line-height: 24px;
        cursor: pointer;
      }
    }
  }
}
</style>
